﻿using System;
using System.Drawing.Imaging;
using System.IO;

namespace Als.Utils.Image
{
    public static class ConverHelper
    {

        #region 二进制转图片

        /// <summary>
        /// 二进制转图片
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static System.Drawing.Image ByteToImage(this byte[] bytes)
        {
            if (bytes == null)
            {
                throw new ArgumentNullException(nameof(bytes));
            }

            System.Drawing.Image image = null;
            using (var stream = new MemoryStream())
            {
                stream.Write(bytes, 0, bytes.Length);
                image = System.Drawing.Image.FromStream(stream);
            }
            return image;
        }

        #endregion

        #region 图片转二进制

        /// <summary>
        /// 图片转二进制
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static byte[] ImageToByte(this System.Drawing.Image image)
        {
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }
            byte[] bytes = null;
            using (var stream = new MemoryStream())
            {
                image.Save(stream, ImageFormat.Jpeg);
                bytes = stream.ToArray();
            }
            return bytes;
        }

        #endregion



    }
}
